//
//  PushAnimator.m
//  UIViewControllerTransitionDemo
//
//  Created by Guo Rui on 2017/7/4.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "PushAnimator.h"
#import "PushViewController.h"
#import "SceneryCell.h"
#import "SceneryDetailViewController.h"

@implementation PushAnimator

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return .3f;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    // 1. 获取源视图控制器 和 目标跳转视图控制器
    PushViewController *fromVc = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    SceneryDetailViewController *toVc = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *containerView = [transitionContext containerView];
    
    // 2. 获取cell中图片的副本，和位置
    SceneryCell *cell = [fromVc cellForSelected];
    UIView *snapView = [cell.pictureImageView snapshotViewAfterScreenUpdates:NO];
    snapView.frame = [containerView convertRect:cell.pictureImageView.frame fromView:cell.pictureImageView.superview];
    
    cell.pictureImageView.hidden = YES;
    
    
    // 3. 获取detail中图片位置
    toVc.view.frame = [transitionContext finalFrameForViewController:toVc];
    toVc.detailImageView.hidden = YES;
    toVc.view.alpha = 0.f;
    
    CGRect snapViewFinalRect = [containerView convertRect:toVc.detailImageView.frame fromView:toVc.detailImageView.superview];
    
    
    // 注意添加顺序
    [containerView addSubview:toVc.view];
    [containerView addSubview:snapView];
   
    
    // 4. 执行动画
    [UIView animateWithDuration:[self transitionDuration:transitionContext]
                          delay:0
         usingSpringWithDamping:.6f
          initialSpringVelocity:1.f
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         snapView.frame = snapViewFinalRect;
                         toVc.view.alpha = 1.f;
                     } completion:^(BOOL finished) {
                         cell.pictureImageView.hidden = NO;
                         toVc.detailImageView.hidden = NO;
                         [snapView removeFromSuperview];
                         [transitionContext completeTransition:YES];
                     }];
}

@end
